package com.gao.alg.geek;

import java.util.HashMap;
import java.util.Map;

public class LRUCache {

    class Node{
        int value;
        int key;
        Node pre;
        Node next;
    }

    private Map<Integer,Node> cache;
    int capacity;
    int size;
    Node head;
    Node tail;

    public LRUCache (int capacity) {
        this.capacity = capacity;
        head = new Node();
        tail = new Node();
        head.next = tail;
        tail.pre = head;
        cache = new HashMap<>(capacity);
    }

    public Integer get(int key){
        Node node = cache.get(key);
        if (node == null) {
            return -1;
        }
        move2Head(node);
        return node.value;
    }

    public void put(int key,int value) {
        Node node = cache.get(key);
        if (node == null) {
            node = new Node();
            node.value = value;
            node.key = key;
            cache.put(key,node);
            add2Head(node);
            size++;
            if (size > capacity) {
                Node tail = removeTail();
                cache.remove(tail.key);
                size--;
            }
        }else {
            node.value = value;
            move2Head(node);
        }
    }

    private Node removeTail() {
        Node node = tail.pre;
        removeNode(node);
        return node;
    }

    private void add2Head(Node node) {
        node.next = head.next;
        head.next.pre = node;
        head.next = node;
        node.pre = head;
    }

    private void move2Head(Node node) {
        removeNode(node);
        add2Head(node);
    }

    private void removeNode(Node node) {
        node.pre.next = node.next;
        node.next.pre = node.pre;
    }
}